namespace DotNetNuke.Services.Log.EventLog
{
    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Users;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Web;

    public class LogController
    {
        private static ReaderWriterLock lockLog = new ReaderWriterLock();
        private const int ReaderLockTimeout = 0x2710;
        private const int WriterLockTimeout = 0x2710;

        public void AddLog(LogInfo objLogInfo)
        {
            try
            {
                objLogInfo.LogCreateDate = DateAndTime.Now;
                objLogInfo.LogServerName = DotNetNuke.Common.Globals.ServerName;
                if (((objLogInfo.LogUserName == "") && (HttpContext.Current != null)) && HttpContext.Current.Request.IsAuthenticated)
                {
                    UserInfo objUserInfo = UserController.GetCurrentUserInfo();
                    objLogInfo.LogUserName = objUserInfo.Membership.Username;
                }
                LoggingProvider.Instance().AddLog(objLogInfo);
            }
            catch (Exception exception1)
            {
                
                Exception exc = exception1;
                try
                {
                    string str = XmlUtils.Serialize(objLogInfo);
                    string f = DotNetNuke.Common.Globals.HostMapPath + @"\Logs\LogFailures.xml.resources";
                    this.WriteLog(f, str);
                }
                catch (Exception exception2)
                {
                    ProjectData.SetProjectError(exception2);
                    Exception exc2 = exception2;
                    
                }
                
            }
        }

        public virtual void AddLogType(LogTypeInfo objLogTypeInfo)
        {
            LoggingProvider.Instance().AddLogType(objLogTypeInfo.LogTypeKey, objLogTypeInfo.LogTypeFriendlyName, objLogTypeInfo.LogTypeDescription, objLogTypeInfo.LogTypeCSSClass, objLogTypeInfo.LogTypeOwner);
        }

        public virtual void AddLogTypeConfigInfo(LogTypeConfigInfo objLogTypeConfigInfo)
        {
            LoggingProvider.Instance().AddLogTypeConfigInfo(objLogTypeConfigInfo.ID, objLogTypeConfigInfo.LoggingIsActive, objLogTypeConfigInfo.LogTypeKey, objLogTypeConfigInfo.LogTypePortalID, objLogTypeConfigInfo.KeepMostRecent, objLogTypeConfigInfo.LogFileName, objLogTypeConfigInfo.EmailNotificationIsActive, Convert.ToString(objLogTypeConfigInfo.NotificationThreshold), Convert.ToString(objLogTypeConfigInfo.NotificationThresholdTime), Convert.ToString((int) objLogTypeConfigInfo.NotificationThresholdTimeType), objLogTypeConfigInfo.MailFromAddress, objLogTypeConfigInfo.MailToAddress);
        }

        public void ClearLog()
        {
            LoggingProvider.Instance().ClearLog();
        }

        public void DeleteLog(LogInfo objLogInfo)
        {
            LoggingProvider.Instance().DeleteLog(objLogInfo);
        }

        public virtual void DeleteLogType(LogTypeInfo objLogTypeInfo)
        {
            LoggingProvider.Instance().DeleteLogType(objLogTypeInfo.LogTypeKey);
        }

        public virtual void DeleteLogTypeConfigInfo(LogTypeConfigInfo objLogTypeConfigInfo)
        {
            LoggingProvider.Instance().DeleteLogTypeConfigInfo(objLogTypeConfigInfo.ID);
        }

        [Obsolete("This method has been replaced with one that supports record paging.")]
        public virtual LogInfoArray GetLog()
        {
            return LoggingProvider.Instance().GetLog();
        }

        [Obsolete("This method has been replaced with one that supports record paging.")]
        public virtual LogInfoArray GetLog(int PortalID)
        {
            return LoggingProvider.Instance().GetLog(PortalID);
        }

        [Obsolete("This method has been replaced with one that supports record paging.")]
        public virtual LogInfoArray GetLog(string LogType)
        {
            return LoggingProvider.Instance().GetLog(LogType);
        }

        [Obsolete("This method has been replaced with one that supports record paging.")]
        public virtual LogInfoArray GetLog(int PortalID, string LogType)
        {
            return LoggingProvider.Instance().GetLog(PortalID, LogType);
        }

        public virtual LogInfoArray GetLog(int PageSize, int PageIndex, ref int TotalRecords)
        {
            return LoggingProvider.Instance().GetLog(PageSize, PageIndex, ref TotalRecords);
        }

        public virtual LogInfoArray GetLog(int PortalID, int PageSize, int PageIndex, ref int TotalRecords)
        {
            return LoggingProvider.Instance().GetLog(PortalID, PageSize, PageIndex, ref TotalRecords);
        }

        public virtual LogInfoArray GetLog(string LogType, int PageSize, int PageIndex, ref int TotalRecords)
        {
            return LoggingProvider.Instance().GetLog(LogType, PageSize, PageIndex, ref TotalRecords);
        }

        public virtual LogInfoArray GetLog(int PortalID, string LogType, int PageSize, int PageIndex, ref int TotalRecords)
        {
            return LoggingProvider.Instance().GetLog(PortalID, LogType, PageSize, PageIndex, ref TotalRecords);
        }

        public virtual ArrayList GetLogTypeConfigInfo()
        {
            return LoggingProvider.Instance().GetLogTypeConfigInfo();
        }

        public virtual LogTypeConfigInfo GetLogTypeConfigInfoByID(string ID)
        {
            return LoggingProvider.Instance().GetLogTypeConfigInfoByID(ID);
        }

        public virtual ArrayList GetLogTypeInfo()
        {
            return LoggingProvider.Instance().GetLogTypeInfo();
        }

        public virtual object GetSingleLog(LogInfo objLogInfo, LoggingProvider.ReturnType objReturnType)
        {
            return LoggingProvider.Instance().GetSingleLog(objLogInfo, objReturnType);
        }

        public bool LoggingIsEnabled(string LogType, int PortalID)
        {
            return LoggingProvider.Instance().LoggingIsEnabled(LogType, PortalID);
        }

        public void PurgeLogBuffer()
        {
            LoggingProvider.Instance().PurgeLogBuffer();
        }

        public virtual bool SupportsEmailNotification()
        {
            bool SupportsEmailNotification=false;
            LoggingProvider.Instance().SupportsEmailNotification();
            return SupportsEmailNotification;
        }

        public virtual bool SupportsInternalViewer()
        {
            bool SupportsInternalViewer=false;
            LoggingProvider.Instance().SupportsInternalViewer();
            return SupportsInternalViewer;
        }

        public virtual void UpdateLogType(LogTypeInfo objLogTypeInfo)
        {
            LoggingProvider.Instance().UpdateLogType(objLogTypeInfo.LogTypeKey, objLogTypeInfo.LogTypeFriendlyName, objLogTypeInfo.LogTypeDescription, objLogTypeInfo.LogTypeCSSClass, objLogTypeInfo.LogTypeOwner);
        }

        public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo objLogTypeConfigInfo)
        {
            LoggingProvider.Instance().UpdateLogTypeConfigInfo(objLogTypeConfigInfo.ID, objLogTypeConfigInfo.LoggingIsActive, objLogTypeConfigInfo.LogTypeKey, objLogTypeConfigInfo.LogTypePortalID, objLogTypeConfigInfo.KeepMostRecent, objLogTypeConfigInfo.LogFileName, objLogTypeConfigInfo.EmailNotificationIsActive, Convert.ToString(objLogTypeConfigInfo.NotificationThreshold), Convert.ToString(objLogTypeConfigInfo.NotificationThresholdTime), Convert.ToString((int) objLogTypeConfigInfo.NotificationThresholdTimeType), objLogTypeConfigInfo.MailFromAddress, objLogTypeConfigInfo.MailToAddress);
        }

        private void WriteLog(string FilePath, string Message)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                int intAttempts=0;
                lockLog.AcquireWriterLock(0x2710);
                while (!((fs != null) | (intAttempts == 100)))
                {
                    intAttempts++;
                    try
                    {
                        fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
                    }
                    catch (IOException exception1)
                    {
                        
                        IOException exc = exception1;
                        Thread.Sleep(1);
                        
                    }
                }
                if (fs == null)
                {
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.Response.Write("An error has occurred writing to the exception log.");
                        HttpContext.Current.Response.End();
                    }
                }
                else
                {
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    long FileLength = fs.Length;
                    if (FileLength > 0L)
                    {
                        fs.Position = FileLength - 9L;
                    }
                    else
                    {
                        Message = "<logs>" + Message;
                    }
                    sw.WriteLine(Message + "</logs>");
                    sw.Flush();
                }
                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
            catch (UnauthorizedAccessException exception2)
            {
                ProjectData.SetProjectError(exception2);
                UnauthorizedAccessException exc = exception2;
                if (HttpContext.Current != null)
                {
                    HttpResponse response = HttpContext.Current.Response;
                    HtmlUtils.WriteHeader(response, "Unauthorized Access Error");
                    string strMessage = exc.Message + " The Windows User Account listed below must have Read/Write Privileges to this path.";
                    HtmlUtils.WriteError(response, FilePath, strMessage);
                    HtmlUtils.WriteFooter(response);
                    response.End();
                }
                
            }
            catch (DirectoryNotFoundException exception3)
            {
                ProjectData.SetProjectError(exception3);
                DirectoryNotFoundException exc = exception3;
                if (HttpContext.Current != null)
                {
                    HttpResponse response = HttpContext.Current.Response;
                    HtmlUtils.WriteHeader(response, "Directory Not Found Error");
                    string strMessage = exc.Message;
                    HtmlUtils.WriteError(response, FilePath, strMessage);
                    HtmlUtils.WriteFooter(response);
                    response.End();
                }
                
            }
            catch (PathTooLongException exception4)
            {
                ProjectData.SetProjectError(exception4);
                PathTooLongException exc = exception4;
                if (HttpContext.Current != null)
                {
                    HttpResponse response = HttpContext.Current.Response;
                    HtmlUtils.WriteHeader(response, "Path Too Long Error");
                    string strMessage = exc.Message;
                    HtmlUtils.WriteError(response, FilePath, strMessage);
                    HtmlUtils.WriteFooter(response);
                    response.End();
                }
                
            }
            catch (IOException exception5)
            {
                ProjectData.SetProjectError(exception5);
                IOException exc = exception5;
                if (HttpContext.Current != null)
                {
                    HttpResponse response = HttpContext.Current.Response;
                    HtmlUtils.WriteHeader(response, "IO Error");
                    string strMessage = exc.Message;
                    HtmlUtils.WriteError(response, FilePath, strMessage);
                    HtmlUtils.WriteFooter(response);
                    response.End();
                }
                
            }
            catch (Exception exception6)
            {
                ProjectData.SetProjectError(exception6);
                Exception exc = exception6;
                if (HttpContext.Current != null)
                {
                    HttpResponse response = HttpContext.Current.Response;
                    HtmlUtils.WriteHeader(response, "Unhandled Error");
                    string strMessage = exc.Message;
                    HtmlUtils.WriteError(response, FilePath, strMessage);
                    HtmlUtils.WriteFooter(response);
                    response.End();
                }
                
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
                lockLog.ReleaseWriterLock();
            }
        }
    }
}

